<template>
  <div>
    <!-- {{  pageModel }} -->
    <!-- <el-button @click="dialogFormVisible = true"
               style="margin-bottom:20px">新建</el-button> -->
    <el-button @click="add"
               style="margin-bottom:20px">新建</el-button>
    <!--<el-form :model="queryForm"-->
    <!--label-width="100px"-->
    <!--:inline="true"-->
    <!--ref="queryForm"-->
    <!--class="demo-ruleForm">-->
    <!--<el-form-item>-->
    <!--<el-button type="primary"-->
    <!--@click="searchData">查询</el-button>-->
    <!--</el-form-item>-->
    <!--</el-form>-->
    <el-dialog title=""
               :visible.sync="dialogFormVisible">
      <el-form :model="form"
               :rules="rules"
               ref="form">
        <el-form-item label="首页图片"
                      prop="backgroundImage">
          <el-upload class="avatar-uploader"
                     :action="uploadImg.action"
                     :on-remove="handleRemove"
                     :on-preview="handlePreview"
                     :on-success="handleSuccess"
                     :limit="1"
                     :before-upload="qwe"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small"
                       type="primary">点击上传</el-button>
            <div slot="tip"
                 class="el-upload__tip">只能上传jpg/png文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="链接地址"
                      prop="linkurl">
          <el-input v-model="form.linkurl"
                    placeholder="请填写链接地址">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="cancel">Cancel</el-button>
        <el-button type="primary"
                   @click="ok">Ok</el-button>
      </span>
    </el-dialog>
    <el-table :data="tableData"
              border
              align="center"
              header-align="center"
              width="100%"
              style="text-align: center;"
              tooltip-effect="dark">
      <el-table-column type="index"
                       width="80">
      </el-table-column>
      <el-table-column prop="backgroundImage"
                       label="图片"
                       width="200">
        <template slot-scope="scope">
          <img :src="'/ActivityWeb/static/'+scope.row.backgroundImage"
               class="img" />
        </template>
      </el-table-column>
      <el-table-column label="链接地址">
        <template slot-scope="scope">
          <a class="activityLink"
             :href="scope.row.linkUrl"
             target="_blank">
            {{scope.row.linkUrl}}
          </a>
        </template>
      </el-table-column>
      <el-table-column prop="createTime"
                       label="创建时间"
                       :formatter="timeFormat">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button class="pan-btn green-btn"
                     @click="delHandle(scope.row, scope.$index)">删除</el-button>
          <el-button class="pan-btn green-btn"
                     @click="up(scope.row, scope.$index)">{{scope.row.topFlag == 0 ? '置顶' :'未置顶'}}</el-button>
          <el-button class="pan-btn green-btn"
                     @click="editHandle(scope.row, scope.$index)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="footer">
      <el-pagination layout="prev, pager, next, jumper"
                     :page-size='10'
                     :total="total"
                     :current-page.sync="currentPageNum"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange">
      </el-pagination>
    </div>
  </div>
</template>
<script>
import request from '@/utils/request'
import { parseTime } from '@/utils/index'

export default {
  name: 'productImgSet',
  props: ['json'],
  data() {
    return {
      queryForm: {
        imgId: ''
      },
      tableData: [],
      activityArr: [],
      dialogFormVisible: false,
      form: {
        linkurl: '',
        id: '',
        backgroundImage: ''
      },
      rules: {
        linkurl: [
          { required: true, message: '请填写链接地址', trigger: 'change' }
        ],
        backgroundImage: [
          { required: true, message: '请上传图片', trigger: 'change' }
        ]
      },
      formLabelWidth: '120px',
      total: 1,
      currentPageNum: 1,
      pageSize: 10,
      pageNum: 0,
      fileList: [],
      uploadImg: {
        action: '/activityConsole/periodicalMessage/uploadImage/'
      },
      labelWidth: '150px',
      guessContentFlag: false,
      dollStyle: '',
      url: '',
      activityId: ''
    }
  },
  mounted() {
    this.select()
    this.search(0)
      console.log(this.json.activityId)
    // console.log(window.location.href.split('?')[1].split('&'))
    console.log(this.GetUrlParam('activityId'))
    this.activityId = this.GetUrlParam('activityId')
    console.log(this.json.activityId)
    // this.$nextTick(function() {
    //   if (this.json.templateMark !== undefined) {
    //     const templateType = this.json.templateMark.toLowerCase()
    //     if (templateType === 'guess') {
    //       this.guessContentFlag = !this.guessContentFlag
    //     }
    //   }
    // })
  },
  computed: {
    getPrizeModel: function() {
      console.log(this.json.pageModel)
      if (this.json.pageModel == 'productImgSet') {
        const _this = this
        this.activityId = this.json.activityId
        if (this.json.prizeId) {
          _this.editFlag = true
          _this.select()
          //   request({
          //     url: '/activityConsole/activity/activityInfoId/' + this.json.activityId + '/prize/id/' + this.json.prizeId,
          //     method: 'get'
          //   }).then(res => {
          //     _this.baseForm = res.data
          //     _this.date = parseTime(res.data.effectiveTime)
          //     _this.renderDate(_this.date)
          //     _this.htmlCon = _this.baseForm.description
          //     _this.htmlCon2 = _this.baseForm.notes
          //     return _this.contentForm = _this.baseForm
          //   })
        }
      }
    }
  },
  methods: {
    GetUrlParam(paraName) {
      var url = document.location.toString()
      var arrObj = url.split('?')

      if (arrObj.length > 1) {
        var arrPara = arrObj[1].split('&')
        var arr

        for (var i = 0; i < arrPara.length; i++) {
          arr = arrPara[i].split('=')

          if (arr != null && arr[0] == paraName) {
            return arr[1]
          }
        }
        return ''
      } else {
        return ''
      }
    },
    up(row) {
      console.log(row)
      var _this = this
      var status = 0
      console.log(row)
      if (row.topFlag === 0) {
        status = 1
        console.log(123)
      } else {
        status = 0
        console.log(456)
      }
      request({
        url: '/activityConsole/activityBargain/topFlagAdvertisingPosition/' + row.id + '?' + 'status=' + status
      }).then(res => {
        _this.search(0)
        _this.$message({
          type: 'success',
          message: res.description
        })
      }).catch(err => {
        console.log(err)
      })
    },
    editHandle(row) {
      console.log(row)
      this.dialogFormVisible = true
      this.form.linkurl = row.linkUrl
      this.form.id = row.id
      this.form.backgroundImage = row.backgroundImage
      console.log(row.linkUrl)
      //   console.log(this.form.linkurl)
      //   return false

      if (row.backgroundImage !== '') {
        this.fileList = []
        const obj = {}
        // string.includes
        console.log(obj.url)
        obj.url = '/ActivityWeb/static/' + row.backgroundImage
        // console.log(obj.url.includes('/ActivityWeb/static/'))
        // if (obj.url.indexOf('/ActivityWeb/static/')) {
        //   console.log(123)
        //   obj.url = row.backgroundImage
        // } else {
        //   console.log(222)
        //   obj.url = '/ActivityWeb/static/' + row.backgroundImage
        // }
        // obj.url = row.backgroundImage
        this.fileList.push(obj)
      }
      console.log(this.fileList)
    },
    timeFormat(row, column) {
      const date = row[column.property]
      return parseTime(date)
    },
    delHandle(row, index) {
      console.log(row)
      const _this = this
      this.$confirm('此操作将永久删除该奖品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'green-btn pan-btn',
        type: 'warning'
      }).then(() => {
        request({
          url: '/activityConsole/activityBargain/delAdvertisingPosition/' + row.id,
          method: 'DELETE'
        }).then(res => {
          if (res.deleteFlag == 'true') {
            _this.tableData.splice(index, 1)
          }
          _this.$message({
            type: 'success',
            message: '删除成功！'
          })
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      console.log(val)
      this.pageNum = parseInt(val) - 1
      this.search(0)
    },
    search(page) {
      const that = this
      console.log()
      that.axios.get('/activityConsole/activityBargain/getAdvertisingPosition?', {
        params: {
          pageNum: page || that.pageNum,
          pageSize: that.pageSize,
          activityId: that.json.activityId
        }
      }).then(function(res) {
        console.log(res.data)
        if (res.data.status === '200') {
          that.tableData = res.data.data
          that.total = parseInt(res.data.description)
        }
      }).catch(function(error) {
        console.log(error)
      })
    },
    querySelectChange() {
      this.pageNum = 0
    },
    select() {
      const _this = this
      _this.axios({
        url: '/activityConsole/activityBargain/getActivityList'
      }).then(res => {
        console.log(res)
        if (res.data.status === '200') {
          _this.activityArr = res.data.data
          console.log(_this.activityArr)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    searchData() {
      this.search(0)
      console.log(123)
    },
    cancel() {
      this.form.linkurl = ''
      this.form.linkurl = null
      this.form.id = ''
      this.form.backgroundImage = ''
      this.fileList = []
      this.dialogFormVisible = false
    },
    add() {
      var _this = this
      console.log(this.fileList)
      console.log(this.form.linkurl)
      //   if (this.fileList[0].url) {
      //     this.fileList[0].url = ''
      //     this.fileList.splice(0)
      //   }
      //   this.form = {}
      setTimeout(function() {
        // console.log(this.fileList)
        _this.form = {}

        _this.dialogFormVisible = true
        console.log(_this.$refs.form)
        _this.$refs.form.resetFields()
      }, 500)
      this.$set(this.form, 'linkurl', '')
      this.form.backgroundImage = ''
      this.fileList = []
      //   this.form = {}
      this.form.linkurl = null
      this.form.linkurl = ''
      console.log(this.form.linkurl)
      console.log(this.fileList)
      //   this.$refs.form.resetFields()
    },
    ok() {
      var _this = this
      //   console.log(_this.fileList)
      const arr = []
      for (var i = 0; i < _this.fileList.length; i++) {
        // console.log(_this.fileList[i].response)
        if (_this.fileList[i].response) {
          arr.push(_this.fileList[i].response.data)
        } else {
          arr.push(_this.fileList[i].url)
        }
      }
      //   console.log(_this.form.backgroundImage)
      //   console.log(_this.form.backgroundImage.toString())
      _this.dollStyle = arr.join()
      console.log(_this.dollStyle)
      //   console.log(this.form)
      console.log(_this.form.id)
      if (_this.form.id === undefined) {
        _this.form.id = ''
      }

      _this.$refs.form.validate(valid => {
        console.log(valid)
        if (valid) {
          request({
            url: '/activityConsole/activityBargain/saveWapImg' + '?url=' + _this.form.backgroundImage + '&' + 'activityId=' + _this.$attrs.json.activityId + '&' + 'linkUrl=' + _this.form.linkurl + '&' + 'id=' + _this.form.id,
            method: 'post'
          }).then(res => {
            // console.log(res)
            if (res.status == '200') {
              _this.search(0)
              _this.cancel()
              setTimeout(function() {
                _this.$refs.form.resetFields()
              }, 100)
              _this.$message({
                type: 'success',
                message: res.description
              })
            } else {
              _this.$message({
                type: 'fail',
                message: res.description
              })
            }
          }).then(err => {
            // _this.form.linkurl = ''
            // console.log(234)
            console.log(err)
          })
        }
      })
    },
    // saveSetHandle() {
    //   const _this = this
    //   request({
    //     url: '/activityConsole/activityBargain/saveWapImg' + '?url=' + _this.dollStyle + '&&' + 'activityId=' + _this.json.activityId,
    //     method: 'post'
    //   }).then(res => {
    //     _this.$message({
    //       type: 'success',
    //       message: res.description
    //     })
    //   }).catch(err => {
    //     console.log(err)
    //   })
    // },
    qwe(file) {
      const _this = this
      const b = file.type.indexOf('image') !== -1
      if (!b) {
        _this.$message({
          type: 'error',
          message: '文件类型不支持'
        })
        return false
      }
      return true
    },
    handleRemove(file, fileList) {
      const _this = this
      console.log('handleRemove:===============================================')
      _this.fileList = fileList
    },
    handlePreview(file) {
      console.log('handlePreview:===============================================')
    },
    handleSuccess(response, file, fileList) {
      const _this = this
      console.log('handlePreviewSuccess:===============================================')
      _this.fileList = fileList
      const arr = []
      for (var i = 0; i < fileList.length; i++) {
        arr.push(fileList[i].response.data)
      }
      _this.form.backgroundImage = arr.join()
      _this.dollStyle = arr.join()
      console.log(_this.form.backgroundImage)
      console.log(_this.dollStyle)
    }
  }
}
</script>
<style scoped>
.el-input >>> .el-input__inner {
  border: none !important;
  line-height: 15px !important;
}
.activityLink {
  cursor: pointer;
  color: #409eff;
}

a.activityLink:hover {
  text-decoration: underline !important;
}

.img {
  width: 100%;
}
</style>
